package com.tanhao.takeaway.controller;

import com.tanhao.takeaway.commom.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class commonController {

    @Value("${takeaway.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String name = file.getOriginalFilename();
        String substring = name.substring(name.lastIndexOf("."));
        File f=new File(path);
        if(!f.exists()){
           f.mkdir();
        }
        String name1=UUID.randomUUID().toString()+substring;
        file.transferTo(new File(path+ name1));

        return R.success(name1);
    }

    @GetMapping("/download")
    public void downFile(HttpServletResponse response,String name){
        try {
            FileInputStream fileInputStream=new FileInputStream(new File(path+name));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("imge/jepg");
            byte[]b=new byte[1024];
            int len=0;
            while((len=fileInputStream.read(b))!=-1){
                outputStream.write(b,0,len);
                outputStream.flush();
            }

            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
